
local assert     = assert
local require    = require    
local bit        = bit
local coroutine  = coroutine
local debug      = debug
local io         = io
local pairs      = pairs
local ipairs     = ipairs
local math       = math
local os         = os
local print      = print
local pcall      = pcall
local xpcall     = xpcall
local rawget     = rawget
local rawset     = rawset
local select     = select
local string     = string
local table      = table
local tonumber   = tonumber
local tostring	 = tostring
local error      = error
local type       = type
local unpack     = unpack
local setmetatable = setmetatable
local getmetatable = getmetatable
local ngx = ngx


----数据变量----
local uu         = require("modules.commhm.utils");
local log        = require("modules.commhm.log");
local ns_time    = require("modules.commhm.time");


-- 时间缓存类 cache
local _M = { _VERSION = '0.12.1' }
local mt = { __index = _M }


function _M.new( self, time_interval_, filename_ )
	log.debug( log.fast() and "call CTimeCache:new, time_interval_=" .. (time_interval_ or 60) );

	local ins_ = {
		last_time         = 0,
		time_interval     = time_interval_    or 60,
		filename          = filename_,                 --是否可以支持存储文件
		data              = nil,		
		version           = nil,
	};
    return setmetatable(ins_, mt);
end


-------------------------------------------------
-- 设置缓存
function _M.set(self, data_)
	if  data_ then
		self.data = data_;	
		self:save_file();
	end
end


-- 获得缓存
function  _M.get(self)
	local now_ = uu.now();
	if  now_ - self.last_time > self.time_interval then
		self.last_time = now_;
		return 1, self.data;       	--过期
	else
		return 0, self.data;   		--有效
	end
end


--存成cache文件
function _M.save_file(self)
	if  self.filename and self.data then	
		local content_ = table.tostring( self.data );
		local file = io.open(self.filename, "w");
		if  file then
			file:write( content_ );
			file:close();
		end		
	end
end


--加载cache文件
function _M.load_file(self)
	if  self.filename then
		local ret = uu.safe_loadTable4File( self.filename, true );		
		if  ret then
			self.data = ret;
			uu.var_dump( self.data );
			log.debug( log.fast() and "load_file ok." );
		else
			log.debug( log.fast() and "load_file fail." );
		end
	end
end


return _M;
